package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.EmployeeUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private HttpSession session;
	@Override
	public List<Category> findAll() {
		
		return categoryMapper.findAll();
	}
	
	@Override
	public ResultInfo delete(String categoryId) {
		//删除前应该先判断当前分类中是否有菜品或者套餐,如果有则不允许删除
		if (categoryMapper.countSetmealByCategoryId(categoryId) > 0){
			return ResultInfo.error("此分类下存在套餐,不允许删除");
		}

		if(categoryMapper.countDishByCategoryId(categoryId) > 0){
			return ResultInfo.error("此分类下存在菜品,不允许删除");
		}

		categoryMapper.delete(categoryId);
		return ResultInfo.success(null);
	}
	
	@Override
	public void deleteById(String categoryId) {
		//删除前应该先判断当前分类中是否有菜品或者套餐,如果有则不允许删除
		if (categoryMapper.countSetmealByCategoryId(categoryId) > 0){
			throw new CustomException("此分类下存在套餐,不允许删除");
		}
		
		if(categoryMapper.countDishByCategoryId(categoryId) > 0){
			
			throw new CustomException("此分类下存在菜品,不允许删除");
		}
		
		categoryMapper.delete(categoryId);
	}
	
	//更新分类
	@Override
	public void update(Category category) {
		
		// category.setUpdateTime(new Date());
		// category.setUpdateUser(EmployeeUtil.getNowUser(session).getId());
		
		
		categoryMapper.update(category);
		
	}
	
	@Override
	public void save(Category category) {
		//雪花算法设置id
		// category.setId(IdUtil.getSnowflake(1,1).nextId());
		//
		// category.setCreateTime(new Date());
		// category.setUpdateTime(new Date());
		//
		// category.setCreateUser(EmployeeUtil.getNowUser(session).getId());
		// category.setUpdateUser(EmployeeUtil.getNowUser(session).getId());
		
		categoryMapper.save(category);
	}
	
	
	@Override
	public List<Category> findByType(Integer type) {
		
		//还是有点不明白,多练习
		//原理?
		//如何运行,如何实现.
		//灵活使用
		
		//组装查询条件
		LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(Category::getType,type);
		
		//查询出查询结果,返回查询列表
		return categoryMapper.selectList(wrapper);
	}
}
